using System;
using System.Text;

using SharpChannel.Core;
using SharpChannel.Core.Packet;

namespace SharpChannel.Server
{
	public class TestServer
	{
		public TestServer ()
		{
		}

		public static void NewClient (object obj)
		{
			TcpClient client = obj as TcpClient;
			if (client != null) {
				int times = new Random().Next() % 10000;
				for(int i = 0; i < times ; ++i)
				{
					StringBuilder sb = new StringBuilder();
					int length = new Random().Next() % 100;
					for(int p = 0; p < length ; ++p)
					{
						sb.Append((char)( p % 26 + 'a'));
					}
					client.SendMessage("message : " + sb.ToString());
					System.Threading.Thread.Sleep(new Random().Next() % 10000);
				}
			}
		}

		public static void Main1(string[] args)
		{
			Console.WriteLine ("Test server start...");
			SharpChannel.Core.TcpServer server = new SharpChannel.Core.TcpServer ();
			server.NewPacketReceived += delegate(object sender, NewPacketArgs e) {
				string message = System.Text.Encoding.UTF8.GetString (e.Data);
                Util.LoggerHelper.GetLogger().Debug("-------------------------server received message  : " + message);
				//Console.WriteLine("send message back to client : " + message);
				e.Session.Send(System.Text.Encoding.UTF8.GetBytes(message + "$$$$"));
			}; 
			server.Start ();
			System.Threading.Thread.Sleep (5000);
			TcpClient []clients = new TcpClient[100];
			for (int i = 0; i < clients.Length; ++i) {
				clients[i] = new TcpClient();
				System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(NewClient));
				clients[i].NewPacketReceived += delegate(object sender, NewPacketArgs e) {
					string message = System.Text.Encoding.UTF8.GetString (e.Data);
					Util.LoggerHelper.GetLogger().Debug("-------------------------client received message  : " + message);
				};;
				thread.Start(clients[i]);
			}
			while (true) {
				if(Console.ReadLine().ToUpper().Equals("EXIT"))
				{
					Console.WriteLine("the server is going to stop...");
					break;
				}
			}
			server.Stop();
			Console.WriteLine("server stopped.");			
		}
	}
}

